package twitterclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.representation.Form;
import com.sun.jersey.oauth.client.OAuthClientFilter;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
import java.awt.Color;
import java.awt.EventQueue;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ListIterator;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.text.Document;
import javax.swing.JOptionPane;
import javax.swing.event.HyperlinkEvent;
import javax.ws.rs.core.MultivaluedMap;
import twitter.twitteroauth.twitterresponse.StatusType;
import twitter.twitteroauth.twitterresponse.Statuses;
import twitter.twitteroauth.twitterresponse.UserType;
import twitter.twitteroauth.twitterresponse.DirectMessageType;
import twitter.twitteroauth.twitterresponse.DirectMessages;

/**
 * @author Kevin Doyle
 * @email  kfrdoyle[at]gmail[dot]com
 */
public class TwitterJFrame extends javax.swing.JFrame {
    static URL oAuthURL = null;//comes from inner class AthoriseConsumer method
    static URL oldURL = null;//prevoius oAuth page on twitter
    static Form requestTokenResponse = null;//Form object from twitter
     StringBuilder str = new StringBuilder(9000);
   Vector<String> vectorTableRows=new Vector<String>(20);

    public TwitterJFrame() {
        /** TwitterJFrame class constructor */
        initComponents(); //Step (1)
        jPMyProfile.setOpaque(false);//prevent sub layer from showing through webpage
        toggleUIButtons(false);//disable UI Buttons
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                collectLoginData(); //Step (2)
            }
        });
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
            try {
                loadAWebPage(); //Step (3)
            } catch (IOException ex) {
                Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    }
    /**End of TwitterJFrame class constructor**/

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TwitterJFrame().setVisible(true);
            }
        });
    }

private void collectLoginData() {
    client = new TwitterClient();
    try {
        client.login();
    } catch (IOException ex) {
        Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UniformInterfaceException ex) {
        Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

    private void loadAWebPage() throws IOException {
        oldURL = oAuthURL;//keep old url for back button
        URL url = new URL(oAuthURL.toString());
        Document doc = jEPWeb.getDocument();
        try {
            jEPWeb.setPage(url);
        } catch (IOException ioException) {
            System.out.println("Error following link");
            jEPWeb.setDocument(doc);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.WARNING: Do NOT modify this code. The content
     * of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPBaseLayer = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jBMentions = new javax.swing.JButton();
        jBMessages = new javax.swing.JButton();
        jBLists = new javax.swing.JButton();
        jBProfile = new javax.swing.JButton();
        jBSearch = new javax.swing.JButton();
        jBTimeLine = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jPPhotoHandle = new javax.swing.JPanel();
        jLUserIcon = new javax.swing.JLabel();
        jLTwitterHandle = new javax.swing.JLabel();
        jLStatusLabel = new javax.swing.JLabel();
        jLLatestTweet = new javax.swing.JLabel();
        jLPLoginTweet = new javax.swing.JLayeredPane();
        jPGetVerifierNum = new javax.swing.JPanel();
        jTFrequestTokenResponse = new javax.swing.JTextField();
        jBGotRequestToken = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jBHistoryBackButton = new javax.swing.JButton();
        jPTweetStatusUpdate = new javax.swing.JPanel();
        jBTweetATweet = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTANewTweet = new javax.swing.JTextArea();
        jLPMainDisplay = new javax.swing.JLayeredPane();
        jSPWebPane = new javax.swing.JScrollPane();
        jEPWeb = new javax.swing.JEditorPane();
        jPMyProfile = new javax.swing.JPanel();
        jLabel16 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel20 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jLRealName = new javax.swing.JLabel();
        jLATTweeter = new javax.swing.JLabel();
        jLHashTwitter = new javax.swing.JLabel();
        jLPhoto = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLTweeterBio = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLTwitterWeb = new javax.swing.JLabel();
        jLTwitterLocation = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLFollowing = new javax.swing.JLabel();
        jLFollowers = new javax.swing.JLabel();
        jPSearchPanel = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();
        jPanel9 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jSeparator3 = new javax.swing.JSeparator();
        jPanel10 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        jSeparator4 = new javax.swing.JSeparator();
        jPanel11 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jSeparator5 = new javax.swing.JSeparator();
        jScrollPane4 = new javax.swing.JScrollPane();
        jList3 = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("___ Project Preachan___");

        jPBaseLayer.setBackground(new java.awt.Color(51, 51, 255));
        jPBaseLayer.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 1, true));
        jPBaseLayer.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        System.out.println("In initComponents method");

        jPanel1.setBackground(new java.awt.Color(102, 153, 255));
        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 1, true));
        jPanel1.setMaximumSize(new java.awt.Dimension(3276, 32767));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jBMentions.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/icon_mentions.gif"))); // NOI18N
        jBMentions.setText("Mentions");
        jBMentions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBMentionsActionPerformed(evt);
            }
        });
        jPanel1.add(jBMentions, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, 170, -1));

        jBMessages.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/icon_messages.gif"))); // NOI18N
        jBMessages.setText("Messages");
        jBMessages.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBMessagesActionPerformed(evt);
            }
        });
        jPanel1.add(jBMessages, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, 170, -1));

        jBLists.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/icon_lists.gif"))); // NOI18N
        jBLists.setText("Lists");
        jBLists.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBListsActionPerformed(evt);
            }
        });
        jPanel1.add(jBLists, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 160, 170, -1));

        jBProfile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/icon_profile.gif"))); // NOI18N
        jBProfile.setText("Profile");
        jBProfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBProfileActionPerformed(evt);
            }
        });
        jPanel1.add(jBProfile, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 210, 170, -1));

        jBSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/icon_search.gif"))); // NOI18N
        jBSearch.setText("Search");
        jBSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSearchActionPerformed(evt);
            }
        });
        jPanel1.add(jBSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, 170, -1));

        jBTimeLine.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/icon_time_line.gif"))); // NOI18N
        jBTimeLine.setText("Home Time Line");
        jBTimeLine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTimeLineActionPerformed(evt);
            }
        });
        jPanel1.add(jBTimeLine, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 170, -1));

        jPBaseLayer.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, 217, 310));

        jPanel4.setBackground(new java.awt.Color(102, 153, 255));
        jPanel4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 1, true));
        jPanel4.setEnabled(false);
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/logo.gif"))); // NOI18N
        jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 20, -1, -1));

        jLabel1.setText("Kevin Doyle © 2011");
        jPanel4.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(52, 78, -1, -1));

        jPBaseLayer.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 420, 217, 150));

        jPPhotoHandle.setBackground(new java.awt.Color(102, 153, 255));
        jPPhotoHandle.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 1, true));

        jLUserIcon.setText("photo");
        jLUserIcon.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
        jLUserIcon.setMaximumSize(new java.awt.Dimension(48, 48));
        jLUserIcon.setMinimumSize(new java.awt.Dimension(48, 48));
        jLUserIcon.setPreferredSize(new java.awt.Dimension(48, 48));

        jLTwitterHandle.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLTwitterHandle.setForeground(new java.awt.Color(255, 255, 255));
        jLTwitterHandle.setText("Twitter Handle");

        jLStatusLabel.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLStatusLabel.setForeground(new java.awt.Color(0, 0, 255));
        jLStatusLabel.setText("Status:");

        jLLatestTweet.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLLatestTweet.setForeground(new java.awt.Color(255, 255, 255));
        jLLatestTweet.setText("status");

        javax.swing.GroupLayout jPPhotoHandleLayout = new javax.swing.GroupLayout(jPPhotoHandle);
        jPPhotoHandle.setLayout(jPPhotoHandleLayout);
        jPPhotoHandleLayout.setHorizontalGroup(
            jPPhotoHandleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPPhotoHandleLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLUserIcon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPPhotoHandleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLTwitterHandle)
                    .addGroup(jPPhotoHandleLayout.createSequentialGroup()
                        .addComponent(jLStatusLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLLatestTweet)))
                .addContainerGap(997, Short.MAX_VALUE))
        );
        jPPhotoHandleLayout.setVerticalGroup(
            jPPhotoHandleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPPhotoHandleLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPPhotoHandleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPPhotoHandleLayout.createSequentialGroup()
                        .addComponent(jLUserIcon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(jPPhotoHandleLayout.createSequentialGroup()
                        .addComponent(jLTwitterHandle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                        .addGroup(jPPhotoHandleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLStatusLabel)
                            .addComponent(jLLatestTweet))
                        .addContainerGap(13, Short.MAX_VALUE))))
        );

        jPBaseLayer.add(jPPhotoHandle, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 13, -1, -1));

        jLPLoginTweet.setBackground(new java.awt.Color(255, 255, 102));
        jLPLoginTweet.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jPGetVerifierNum.setBackground(new java.awt.Color(102, 153, 255));

        jTFrequestTokenResponse.setFont(new java.awt.Font("Tahoma", 1, 14));
        jTFrequestTokenResponse.setDragEnabled(true);

        jBGotRequestToken.setText("OK");
        jBGotRequestToken.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBGotRequestTokenActionPerformed(evt);
            }
        });

        jLabel5.setText("Enter 7 digit number, then click [OK]");

        jBHistoryBackButton.setText("<<Back");
        jBHistoryBackButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBHistoryBackButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPGetVerifierNumLayout = new javax.swing.GroupLayout(jPGetVerifierNum);
        jPGetVerifierNum.setLayout(jPGetVerifierNumLayout);
        jPGetVerifierNumLayout.setHorizontalGroup(
            jPGetVerifierNumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPGetVerifierNumLayout.createSequentialGroup()
                .addContainerGap(542, Short.MAX_VALUE)
                .addGroup(jPGetVerifierNumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jTFrequestTokenResponse)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jBGotRequestToken, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(107, 107, 107)
                .addComponent(jBHistoryBackButton)
                .addGap(203, 203, 203))
        );
        jPGetVerifierNumLayout.setVerticalGroup(
            jPGetVerifierNumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPGetVerifierNumLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addGap(3, 3, 3)
                .addGroup(jPGetVerifierNumLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFrequestTokenResponse, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBGotRequestToken, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBHistoryBackButton))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jPGetVerifierNum.setBounds(0, 0, 1170, 80);
        jLPLoginTweet.add(jPGetVerifierNum, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jPTweetStatusUpdate.setBackground(new java.awt.Color(102, 153, 255));
        jPTweetStatusUpdate.setFocusable(false);
        jPTweetStatusUpdate.setOpaque(false);
        jPTweetStatusUpdate.setRequestFocusEnabled(false);
        jPTweetStatusUpdate.setVerifyInputWhenFocusTarget(false);

        jBTweetATweet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/twitterclient/icon_tweet.gif"))); // NOI18N
        jBTweetATweet.setText("  Tweet!");
        jBTweetATweet.setEnabled(false);
        jBTweetATweet.setFocusPainted(false);
        jBTweetATweet.setFocusable(false);
        jBTweetATweet.setMaximumSize(new java.awt.Dimension(104, 41));
        jBTweetATweet.setMinimumSize(new java.awt.Dimension(104, 41));
        jBTweetATweet.setPreferredSize(new java.awt.Dimension(101, 41));
        jBTweetATweet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBTweetATweetActionPerformed(evt);
            }
        });

        jScrollPane2.setEnabled(false);
        jScrollPane2.setFocusable(false);
        jScrollPane2.setOpaque(false);
        jScrollPane2.setRequestFocusEnabled(false);
        jScrollPane2.setWheelScrollingEnabled(false);

        jTANewTweet.setColumns(20);
        jTANewTweet.setFont(new java.awt.Font("Monospaced", 1, 13));
        jTANewTweet.setForeground(new java.awt.Color(0, 51, 204));
        jTANewTweet.setLineWrap(true);
        jTANewTweet.setRows(3);
        jTANewTweet.setToolTipText("120 Maximum characters");
        jTANewTweet.setEnabled(false);
        jScrollPane2.setViewportView(jTANewTweet);

        javax.swing.GroupLayout jPTweetStatusUpdateLayout = new javax.swing.GroupLayout(jPTweetStatusUpdate);
        jPTweetStatusUpdate.setLayout(jPTweetStatusUpdateLayout);
        jPTweetStatusUpdateLayout.setHorizontalGroup(
            jPTweetStatusUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPTweetStatusUpdateLayout.createSequentialGroup()
                .addGap(230, 230, 230)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 573, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jBTweetATweet, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(222, Short.MAX_VALUE))
        );
        jPTweetStatusUpdateLayout.setVerticalGroup(
            jPTweetStatusUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPTweetStatusUpdateLayout.createSequentialGroup()
                .addGroup(jPTweetStatusUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPTweetStatusUpdateLayout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addComponent(jBTweetATweet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPTweetStatusUpdateLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPTweetStatusUpdate.setBounds(0, 0, 1170, 79);
        jLPLoginTweet.add(jPTweetStatusUpdate, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jPBaseLayer.add(jLPLoginTweet, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 592, 1170, 80));

        jSPWebPane.setBorder(null);

        jEPWeb.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 1, true));
        jEPWeb.setContentType("text/html");
        jEPWeb.setEditable(false);
        jEPWeb.setText("<html>\r\n  <head>\r\n\r\n  </head>\r\n  <body bgcolor=\"white\">\r\n    <p style=\"margin-top: 0\">\r\n      \r\n    </p>\r\n  </body>\r\n</html>\r\n");
        jEPWeb.setDoubleBuffered(true);
        jEPWeb.setDragEnabled(true);
        jEPWeb.setFocusTraversalPolicyProvider(true);
        jEPWeb.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
            public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
                jEPWebHyperlinkUpdate(evt);
            }
        });
        jSPWebPane.setViewportView(jEPWeb);

        jSPWebPane.setBounds(0, 0, 940, 470);
        jLPMainDisplay.add(jSPWebPane, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jPMyProfile.setBackground(new java.awt.Color(255, 255, 255));
        jPMyProfile.setEnabled(false);
        jPMyProfile.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel16.setText("jLabel16");
        jPMyProfile.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(236, 484, -1, -1));

        jLabel17.setText("jLabel17");
        jPMyProfile.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(586, 484, -1, -1));

        jPanel2.setBackground(new java.awt.Color(102, 153, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));
        jPanel2.setPreferredSize(new java.awt.Dimension(276, 127));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel20.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel20.setText("#");
        jPanel2.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(78, 79, -1, -1));

        jLabel19.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel19.setText("@");
        jPanel2.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(78, 41, -1, -1));

        jLabel18.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel18.setText("Name");
        jPanel2.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(78, 13, -1, -1));

        jLRealName.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLRealName.setText("Name");
        jPanel2.add(jLRealName, new org.netbeans.lib.awtextra.AbsoluteConstraints(134, 13, -1, -1));

        jLATTweeter.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLATTweeter.setText("@");
        jPanel2.add(jLATTweeter, new org.netbeans.lib.awtextra.AbsoluteConstraints(131, 41, -1, -1));

        jLHashTwitter.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLHashTwitter.setText("#");
        jPanel2.add(jLHashTwitter, new org.netbeans.lib.awtextra.AbsoluteConstraints(131, 79, -1, -1));

        jLPhoto.setText("photo");
        jLPhoto.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 1, true));
        jLPhoto.setMaximumSize(new java.awt.Dimension(48, 48));
        jLPhoto.setMinimumSize(new java.awt.Dimension(48, 48));
        jLPhoto.setPreferredSize(new java.awt.Dimension(48, 48));
        jPanel2.add(jLPhoto, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 33, -1, -1));
        jPanel2.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 33, 204, -1));

        jSeparator2.setPreferredSize(new java.awt.Dimension(60, 5));
        jPanel2.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 60, 204, -1));

        jPMyProfile.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 920, 100));

        jPanel3.setBackground(new java.awt.Color(102, 153, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));

        jButton1.setText("EDIT PROFILE...");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jButton1)
                .addContainerGap(786, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

        jPMyProfile.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 120, 920, -1));

        jPanel5.setBackground(new java.awt.Color(102, 153, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));
        jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLTweeterBio.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLTweeterBio.setText("bio");
        jPanel5.add(jLTweeterBio, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 10, -1, -1));

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel8.setText("Bio");
        jPanel5.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, -1, -1));

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel9.setText("Location");
        jPanel5.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, -1, -1));

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel10.setText("Web");
        jPanel5.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, -1, -1));

        jLTwitterWeb.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLTwitterWeb.setText("web");
        jPanel5.add(jLTwitterWeb, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 70, -1, -1));

        jLTwitterLocation.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLTwitterLocation.setText("location");
        jPanel5.add(jLTwitterLocation, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 40, -1, -1));

        jPMyProfile.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 180, 920, 100));

        jPanel6.setBackground(new java.awt.Color(102, 153, 255));
        jPanel6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));
        jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton2.setText("Tweets");
        jPanel6.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));

        jButton3.setText("Mentions");
        jPanel6.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 10, -1, -1));

        jButton4.setText("Favorites");
        jPanel6.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 10, -1, -1));

        jPMyProfile.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 290, 920, 70));

        jPanel7.setBackground(new java.awt.Color(102, 153, 255));
        jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));
        jPanel7.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel14.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel14.setText("Following");
        jPanel7.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 10, -1, -1));

        jLabel15.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel15.setText("Followers");
        jPanel7.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 10, -1, -1));

        jLFollowing.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLFollowing.setText("--");
        jPanel7.add(jLFollowing, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, -1, -1));

        jLFollowers.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLFollowers.setText("--");
        jPanel7.add(jLFollowers, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 30, -1, -1));

        jPMyProfile.add(jPanel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 370, 920, 90));

        jPMyProfile.setBounds(0, 0, 940, 470);
        jLPMainDisplay.add(jPMyProfile, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jPSearchPanel.setBackground(new java.awt.Color(255, 255, 255));
        jPSearchPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel8.setBackground(new java.awt.Color(102, 153, 255));
        jPanel8.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));

        jTextField1.setText("search");

        jButton5.setText("OK");

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton5)
                .addContainerGap(723, Short.MAX_VALUE))
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton5))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        jPSearchPanel.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 920, 50));

        jPanel9.setBackground(new java.awt.Color(102, 153, 255));
        jPanel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel3.setText("Saved Searches");

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(180, Short.MAX_VALUE))
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(206, Short.MAX_VALUE))
        );

        jPSearchPanel.add(jPanel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 300, 390));

        jPanel10.setBackground(new java.awt.Color(102, 153, 255));
        jPanel10.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));

        jList2.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(jList2);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel4.setText("Trending Now");

        javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
        jPanel10.setLayout(jPanel10Layout);
        jPanel10Layout.setHorizontalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE))
                .addContainerGap())
            .addComponent(jSeparator4, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
        );
        jPanel10Layout.setVerticalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(207, Short.MAX_VALUE))
        );

        jPSearchPanel.add(jPanel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 70, 300, 390));

        jPanel11.setBackground(new java.awt.Color(102, 153, 255));
        jPanel11.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255)));
        jPanel11.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel6.setText("Top Tweets");
        jPanel11.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
        jPanel11.add(jSeparator5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 30, 298, 10));

        jList3.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane4.setViewportView(jList3);

        jPanel11.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, 270, -1));

        jPSearchPanel.add(jPanel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 70, 300, 390));

        jPSearchPanel.setBounds(0, 0, 940, 470);
        jLPMainDisplay.add(jPSearchPanel, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jPBaseLayer.add(jLPMainDisplay, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 100, 940, 470));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPBaseLayer, javax.swing.GroupLayout.DEFAULT_SIZE, 1196, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPBaseLayer, javax.swing.GroupLayout.DEFAULT_SIZE, 693, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jEPWebHyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {//GEN-FIRST:event_jEPWebHyperlinkUpdate
    HyperlinkEvent.EventType type = evt.getEventType();
    final URL url = evt.getURL();
    if (type == HyperlinkEvent.EventType.ACTIVATED) {
        Runnable runner = new Runnable() {
            @Override
    public void run() {
        //Log in, get tokens, and append the tokens to the consumer and secret keys
        client.initOAuth();
        // Retain reference to original
        Document doc = jEPWeb.getDocument();
        try {
            jEPWeb.setPage(url);
        } catch (IOException ioException) {
            JOptionPane.showMessageDialog(null, "Error following link",
                    "Invalid link", JOptionPane.ERROR_MESSAGE);
            jEPWeb.setDocument(doc);
        }
    }
};
EventQueue.invokeLater(runner);
}
}//GEN-LAST:event_jEPWebHyperlinkUpdate


private void jBHistoryBackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBHistoryBackButtonActionPerformed
    //History navigation button for travelling back in surfing time
    URL url = null;
    try {
        url = new URL(oldURL.toString());
    } catch (MalformedURLException ex) {
        Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    Document doc = jEPWeb.getDocument();
    try {
        jEPWeb.setPage(url);
    } catch (IOException ioException) {
        JOptionPane.showMessageDialog(null, "Error following link",
        "Error following link", JOptionPane.ERROR_MESSAGE);
        jEPWeb.setDocument(doc);
    }

}//GEN-LAST:event_jBHistoryBackButtonActionPerformed

private void jBTimeLineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTimeLineActionPerformed
//Home/User TimeLine Button and functions to get & show the homeTimeLine
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            jLPMainDisplay.moveToBack(jSPWebPane);
             jPMyProfile.setVisible(false);
            jPSearchPanel.setVisible(false);
        jSPWebPane.setVisible(true);
        client.initOAuth();
        vectorTableRows.clear();
        vectorTableRows.add("<table border='0' width='932'>");
        String homeTimeLineTweets = "";
                Statuses userStatuses = client.getFriendsTimeline(Statuses.class, null, null, null, "20");//collection of tweets
        for (StatusType userStatusType : userStatuses.getStatus()) {
         homeTimeLineTweets = "<tr bgcolor='#ffffff'><td width='49' bgcolor='#ffffff'><img src='" + userStatusType.getUser().getProfileImageUrl() + "' height='48' width='48'></td><td bgcolor='#ffffff'><font face='Arial' size='4'><b>" + userStatusType.getUser().getScreenName().toUpperCase() + "</b><br>" + userStatusType.getText() + "</font><hr></td></tr>";
         vectorTableRows.add(homeTimeLineTweets);
        }
        vectorTableRows.add("<table>");
        parseTweet();//send string of tweets off for parsing
    }
});

}//GEN-LAST:event_jBTimeLineActionPerformed

private void jBGotRequestTokenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBGotRequestTokenActionPerformed
// OK Button on get verifier code jPanel
    try {
        client.oauth_verifier2 = jTFrequestTokenResponse.getText();
        client.login_phase_2(requestTokenResponse);
        jTFrequestTokenResponse.setText("");//clear the text field
        jLPLoginTweet.moveToFront(jPTweetStatusUpdate);
        jPTweetStatusUpdate.setOpaque(true);
        jPTweetStatusUpdate.setFocusable(true);
        jPTweetStatusUpdate.setEnabled(true);
        jPTweetStatusUpdate.setRequestFocusEnabled(true);
        jPTweetStatusUpdate.setVerifyInputWhenFocusTarget(true);
        jPTweetStatusUpdate.setVisible(true);
        jPGetVerifierNum.setVisible(false);
        jBHistoryBackButton.setFocusable(false);
        jBHistoryBackButton.setFocusPainted(false);
        jBTweetATweet.setEnabled(true);
        jBTweetATweet.setFocusable(true);
        jBTweetATweet.setFocusPainted(true);
        jScrollPane2.setRequestFocusEnabled(true);
        jScrollPane2.setOpaque(true);
        jScrollPane2.setEnabled(true);
        jScrollPane2.setWheelScrollingEnabled(true);
        jTANewTweet.setEnabled(true);
        initUserData();//start populating UI with account info
        jEPWeb.setBackground(Color.white);
        toggleUIButtons(true);//enable UI Buttons
    } catch (IOException ex) {
        Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UniformInterfaceException ex) {
        Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}//GEN-LAST:event_jBGotRequestTokenActionPerformed

private void jBTweetATweetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTweetATweetActionPerformed
// From the publish tweet button:
    String rawStatus = jTANewTweet.getText().trim();
    client.makeOAuthRequestUnique();
    String status = rawStatus;
    client.updateStatus(String.class, status, null);
    jTANewTweet.setText(" ");
}//GEN-LAST:event_jBTweetATweetActionPerformed

private void jBProfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBProfileActionPerformed
//This is for Profile button Twitter Profile Info
    jLPMainDisplay.moveToFront(jPMyProfile);
    jPMyProfile.setEnabled(true);
    jSPWebPane.setEnabled(false);
   //  jPMyProfile.setOpaque(true);
   // jSPWebPane.setOpaque(false);
       jPMyProfile.setVisible(true);
            jPSearchPanel.setVisible(false);
            //jSPWebPane.setWheelScrollingEnabled(false);
            jSPWebPane.setVisible(false);
     java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Bring st back into scope at method level KD 15/07/11
                StatusType st = new StatusType();
                //Log in, get tokens, and append the tokens to the consumer and secret keys
                client.initOAuth();
                String twitterUserID="kevindoyletweet";
        UserType userTypes=client.showUsersById(UserType.class, twitterUserID);
               //Get a UserType object from the StatusType object, get the URL of that
                //user's icon, and display that icon in the JLabel

           //  UserType user = st.getUser();
              //  String iconSrc = user.getProfileImageUrl();
             String iconSrc=userTypes.getProfileImageUrl();
             URL iconUrl = null;
                try {
                    iconUrl = new URL(iconSrc);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                ImageIcon icon = new ImageIcon(iconUrl, userTypes.getScreenName());
               jLPhoto.setIcon(icon);
               jLRealName.setText(userTypes.getName());
               jLATTweeter.setText(userTypes.getScreenName());
               jLHashTwitter.setText(userTypes.getId());
               jLTwitterLocation.setText(userTypes.getLocation());
               jLFollowing.setText(userTypes.getFriendsCount().toString());
               jLFollowers.setText(userTypes.getFollowersCount().toString());
               jLTweeterBio.setText(userTypes.getDescription());
               jLTwitterWeb.setText(userTypes.getUrl());

            }
        });

}//GEN-LAST:event_jBProfileActionPerformed

private void jBMentionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBMentionsActionPerformed
// Mentions Button lists where @kevindoyletweet is used in a mentions Timeline
        java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            jLPMainDisplay.moveToFront(jSPWebPane);
            jPMyProfile.setVisible(false);
            jPSearchPanel.setVisible(false);
            jSPWebPane.setVisible(true);
        client.initOAuth();
        vectorTableRows.clear();
        vectorTableRows.add("<table border='0' width='932'>");
        String homeTimeLineTweets = "";
                Statuses userMentions = client.getMentions(Statuses.class, null, null, null, "20");//collection of tweets
        for (StatusType userStatusType : userMentions.getStatus()) {
         homeTimeLineTweets = "<tr bgcolor='#ffffff'><td width='49' bgcolor='#ffffff'><img src='" + userStatusType.getUser().getProfileImageUrl() + "' height='48' width='48'></td><td bgcolor='#ffffff'><font face='Arial' size='4'><b>" + userStatusType.getUser().getScreenName().toUpperCase() + "</b><br>" + userStatusType.getText() + "</font><hr></td></tr>";
         vectorTableRows.add(homeTimeLineTweets);
        }
        vectorTableRows.add("<table>");
        parseTweet();//send string of tweets off for parsing
    }
});
}//GEN-LAST:event_jBMentionsActionPerformed

private void jBSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSearchActionPerformed
// TODO add your handling code here:
      jPMyProfile.setVisible(false);
            jPSearchPanel.setVisible(true);
    jLPMainDisplay.moveToFront(jPSearchPanel);

}//GEN-LAST:event_jBSearchActionPerformed

    private void jBMessagesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBMessagesActionPerformed
    // Messages Button lists private messages to @kevindoyletweet 
        java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            jLPMainDisplay.moveToFront(jSPWebPane);
            jPMyProfile.setVisible(false);
            jPSearchPanel.setVisible(false);
            jSPWebPane.setVisible(true);
        client.initOAuth();
        vectorTableRows.clear();
        vectorTableRows.add("<table border='0' width='932'>");
        String homeTimeLineTweets = "";
       DirectMessages userDirectMessage = client.getDirectMessagesToMe(DirectMessages.class, null, null,null);//collection of tweets
      
       for(DirectMessageType userDirectMessageType: userDirectMessage.getDirectMessage()){
        homeTimeLineTweets = "<tr bgcolor='#ffffff'><td width='49' bgcolor='#ffffff'><img src='" + userDirectMessageType.getSender().getProfileImageUrl() + "' height='48' width='48'></td><td bgcolor='#ffffff'><font face='Arial' size='4'><b>" + userDirectMessageType.getSender().getScreenName().toUpperCase() + "</b><br>" + userDirectMessageType.getText() + "</font><hr></td></tr>";
        vectorTableRows.add(homeTimeLineTweets);
        }
        
        vectorTableRows.add("<table>");
        parseTweet();//send string of tweets off for parsing
    }
});
    }//GEN-LAST:event_jBMessagesActionPerformed

    private void jBListsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBListsActionPerformed
    //Lists Button lists any lists of tweople I create 
        java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            jLPMainDisplay.moveToFront(jSPWebPane);
            jPMyProfile.setVisible(false);
            jPSearchPanel.setVisible(false);
            jSPWebPane.setVisible(true);
        client.initOAuth();
        vectorTableRows.clear();
        vectorTableRows.add("<table border='0' width='932'>");
              
        
        vectorTableRows.add("<br> Hello Dog");
        parseTweet();//send string of tweets off for parsing
    }
});
    }//GEN-LAST:event_jBListsActionPerformed

     /***
     * @param toggleYN Allows Enable/Disable of UI Components
     * @return void
     */
private void toggleUIButtons(boolean toggleYN){
    boolean toggle=toggleYN;
    jBTimeLine.setEnabled(toggle);
    jBMentions.setEnabled(toggle);
    jBMessages.setEnabled(toggle);
    jBLists.setEnabled(toggle);
    jBProfile.setEnabled(toggle);
    jBSearch.setEnabled(toggle);
}
    private void parseTweet() {
        ListIterator iter = vectorTableRows.listIterator();
        String tokenisedTextString = "";
        while (iter.hasNext()) {
              StringTokenizer st = new StringTokenizer(iter.next().toString());
              while (st.hasMoreTokens()) {
            String key = st.nextToken();
            if (key.startsWith("#")) {
                key = "<a href='https://twitter.com/#!/search?q=%23" + key + "'>" + key + "</a>";
            } else if (key.startsWith("@")) {
                key = "<a href='http://twitter.com/" + key + "'>" + key + "</a>";
            } else if (key.startsWith("http")) {
                key = "<a href='" + key + "'>" + key + "</a>";
            } else if (key.startsWith("https")) {
                key = "<a href='" + key + "'>" + key + "</a>";
            }
            tokenisedTextString += key + " ";
        }
            jEPWeb.setText("");
            jEPWeb.setText(tokenisedTextString);
      }
    }

    private void initUserData() throws MalformedURLException, IOException {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                //Bring st back into scope at method level KD 15/07/11
                StatusType st = new StatusType();
                //Log in, get tokens, and append the tokens to the consumer and secret keys
                client.initOAuth();
                //Call getUserTimeline, get a list of statuses, pass the most recent
                //status as a StatusType object, and display the text of that object
                //in the JTextField
                Statuses statuses = client.getUserTimeline(Statuses.class, null, null, null, "1");
                st = statuses.getStatus().get(0);
                //try decoding the text before showing it in the ui 22/07/11 - KD
                jLLatestTweet.setText(st.getText().trim());
                //Get a UserType object from the StatusType object, get the URL of that
                //user's icon, and display that icon in the JLabel
                UserType user = st.getUser();
                String iconSrc = user.getProfileImageUrl();
                URL iconUrl = null;
                try {
                    iconUrl = new URL(iconSrc);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                ImageIcon icon = new ImageIcon(iconUrl, user.getScreenName());
                jLUserIcon.setIcon(icon);
                jLTwitterHandle.setText(user.getScreenName());
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBGotRequestToken;
    private javax.swing.JButton jBHistoryBackButton;
    private javax.swing.JButton jBLists;
    private javax.swing.JButton jBMentions;
    private javax.swing.JButton jBMessages;
    private javax.swing.JButton jBProfile;
    private javax.swing.JButton jBSearch;
    private javax.swing.JButton jBTimeLine;
    private javax.swing.JButton jBTweetATweet;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JEditorPane jEPWeb;
    private javax.swing.JLabel jLATTweeter;
    private javax.swing.JLabel jLFollowers;
    private javax.swing.JLabel jLFollowing;
    private javax.swing.JLabel jLHashTwitter;
    private javax.swing.JLabel jLLatestTweet;
    private javax.swing.JLayeredPane jLPLoginTweet;
    private javax.swing.JLayeredPane jLPMainDisplay;
    private javax.swing.JLabel jLPhoto;
    private javax.swing.JLabel jLRealName;
    private javax.swing.JLabel jLStatusLabel;
    private javax.swing.JLabel jLTweeterBio;
    private javax.swing.JLabel jLTwitterHandle;
    private javax.swing.JLabel jLTwitterLocation;
    private javax.swing.JLabel jLTwitterWeb;
    private javax.swing.JLabel jLUserIcon;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JList jList3;
    private javax.swing.JPanel jPBaseLayer;
    private javax.swing.JPanel jPGetVerifierNum;
    private javax.swing.JPanel jPMyProfile;
    private javax.swing.JPanel jPPhotoHandle;
    private javax.swing.JPanel jPSearchPanel;
    private javax.swing.JPanel jPTweetStatusUpdate;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jSPWebPane;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JTextArea jTANewTweet;
    private javax.swing.JTextField jTFrequestTokenResponse;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
    /**
     * private TwitterClient client This points to the class below and gives
     * us access to a static TwitterClient object in memory
     */
    private TwitterClient client;

    static class TwitterClient {

        private WebResource webResource;
        private Client client;
        private static final String BASE_URI = "https://twitter.com";

        public TwitterClient() {
            com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig(); // SSL configuration
            config.getProperties().put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), getSSLContext()));
            client = Client.create(config);
            String resourcePath = "statuses";
            //change this as not all resources are a status
            //webResource = client.resource(BASE_URI).path(resourcePath);
            webResource = client.resource(BASE_URI);
        }
        private static final String OAUTH_BASE_URL = "http://twitter.com/oauth";
        /**
         * Please, specify the consumer_key string obtained from service API pages
         */
        private static final String CONSUMER_KEY = "uDgRAVEtjxsBtR52PqAA";
        /**
         * Please, specify the consumer_secret string obtained from service API pages
         */
        private static final String CONSUMER_SECRET = "85zAfuclWgW7cZTmgqVUq2JEicD6kV6sCOH6SIIZU";
      //  private String oauth_verifier;//retriev from dialog
        private OAuthParameters oauth_params;
        private OAuthSecrets oauth_secrets;
        private OAuthClientFilter oauth_filter;
        private String oauth_access_token;
        private String oauth_access_token_secret;
        String oauth_verifier2=null;//taken from webpage via OK button event

        //public void setResourcePath(String format) {
          //  String resourcePath = java.text.MessageFormat.format("statuses/user_timeline.{0}", new Object[]{format});
            //webResource = client.resource(BASE_URI).path(resourcePath);
        //}

        /**
         * @param responseType Class representing the response
         * @param since query parameter
         * @param since_id query parameter
         * @param page query parameter
         * @param count query parameter
         * @return response object (instance of responseType class)
         */
         //This function returns my tweets
        public <T> T getUserTimeline(Class<T> responseType, String since, String since_id, String page, String count) throws UniformInterfaceException {
            String[] queryParamNames = new String[]{"since", "since_id", "page", "count"};
            String[] queryParamValues = new String[]{since, since_id, page, "count"};
            return webResource.path("/statuses/user_timeline.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
        }

        //this function returns tweets that mention me
        public <T> T getMentions(Class<T> responseType, String since, String since_id, String page, String count) throws UniformInterfaceException {
            String[] queryParamNames = new String[]{"since", "since_id", "page", "count"};
            String[] queryParamValues = new String[]{since, since_id, page, "count"};
            return webResource.path("/statuses/mentions.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
        }

         public <T> T getDirectMessagesToMe(Class<T> responseType, String since, String since_id, String page) throws UniformInterfaceException {
            String[] queryParamNames = new String[]{"since", "since_id", "page"};
            String[] queryParamValues = new String[]{since, since_id, page};
            return webResource.path("/direct_messages.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
        }
         
        
            //this function returns the tweets of people I follow
            public <T> T getFriendsTimeline(Class<T> responseType, String since, String since_id, String page, String count) throws UniformInterfaceException {
            String[] queryParamNames = new String[]{"since", "since_id", "page", "count"};
            String[] queryParamValues = new String[]{since, since_id, page, count};
            //updated endpoint as per twitter API change 19/07/11 -KD
            return webResource.path("/statuses/home_timeline.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
        }
            //this function allows me to update my status
            public <T> T updateStatus(Class<T> responseType, String status, String in_reply_to_status_id) throws UniformInterfaceException {
            String[] formParamNames = new String[]{"status", "in_reply_to_status_id"};
            String[] formParamValues = new String[]{status, in_reply_to_status_id};
            return webResource.path("/statuses/update.xml").type(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED).post(responseType, getQueryOrFormParams(formParamNames, formParamValues));
        }
            /**
         * @param responseType Class representing the response
         * @param email query parameter
         * @return response object (instance of responseType class)
         */
        public <T> T showUsersById(Class<T> responseType, String screen_name) throws UniformInterfaceException {
            String[] queryParamNames = new String[]{"screen_name"};
            String[] queryParamValues = new String[]{screen_name};
            return webResource.path("/users/show.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
        }

        private MultivaluedMap getQueryOrFormParams(String[] paramNames, String[] paramValues) {
            MultivaluedMap<String, String> qParams = new com.sun.jersey.api.representation.Form();//Debug this String String
            for (int i = 0; i < paramNames.length; i++) {
                if (paramValues[i] != null) {
                    qParams.add(paramNames[i], paramValues[i]);
                }
            }
            return qParams;
        }

        public void close() {
            client.destroy();
        }

        /**
         * You need to call this method at the beginning to authorize the application to work with user data.
         * The method obtains the OAuth access token string, that is appended to each API request later.
         */
        public void login() throws IOException, UniformInterfaceException {
            Form requestTokenResponse = getOAuthRequestToken();
            TwitterJFrame.requestTokenResponse=requestTokenResponse;//pass rTR to outter class so outer class can call loginPhase2
            String temp=getOAuthURL(requestTokenResponse);//playing ball with Jersey just to rob oAuthURL
            }

            //seperate these here
            public void login_phase_2(Form requestTokenResponse) throws IOException, UniformInterfaceException {
            String oauth_verifier = authorizeConsumer(requestTokenResponse);
            Form accessTokenResponse = getOAuthAccessToken(requestTokenResponse, oauth_verifier);
            oauth_access_token_secret = accessTokenResponse.getFirst("oauth_token_secret");
            oauth_access_token = accessTokenResponse.getFirst("oauth_token");
            }

        private Form getOAuthRequestToken() throws UniformInterfaceException {
            WebResource resource = client.resource(OAUTH_BASE_URL).path("request_token");
            oauth_params = new OAuthParameters().consumerKey(CONSUMER_KEY).signatureMethod(com.sun.jersey.oauth.signature.HMAC_SHA1.NAME).version("1.0").nonce().timestamp();
            oauth_secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
            oauth_filter = new OAuthClientFilter(client.getProviders(), oauth_params, oauth_secrets);
            resource.addFilter(oauth_filter);
            return resource.get(Form.class);
        }

        private Form getOAuthAccessToken(Form requestTokenResponse, String oauth_verifier) throws UniformInterfaceException {
            WebResource resource = client.resource(OAUTH_BASE_URL).path("access_token");
            oauth_params.token(requestTokenResponse.getFirst("oauth_token")).signatureMethod(com.sun.jersey.oauth.signature.HMAC_SHA1.NAME).version("1.0").nonce().timestamp().verifier(oauth_verifier);
            oauth_secrets.tokenSecret(requestTokenResponse.getFirst("oauth_token_secret"));
            resource.addFilter(oauth_filter);
            return resource.get(Form.class);
        }

        /**
         * The method sets the OAuth parameters for webResource.
         * The method needs to be called after login() method, or when the webResource path is changed
         */
        public void initOAuth() {
            oauth_params = new OAuthParameters().consumerKey(CONSUMER_KEY).token(oauth_access_token).signatureMethod(com.sun.jersey.oauth.signature.HMAC_SHA1.NAME).version("1.0").nonce().timestamp();
            oauth_secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET).tokenSecret(oauth_access_token_secret);
            oauth_filter = new OAuthClientFilter(client.getProviders(), oauth_params, oauth_secrets);
            webResource.addFilter(oauth_filter);
        }

       
        public void makeOAuthRequestUnique() {
            if (oauth_params != null) {
                oauth_params.nonce().timestamp();
            }
        }

       private String getOAuthURL(Form requestTokenResponse)throws IOException{
           URL url =null;
           String strURLstr="";
            try {
              URI uri = new URI("http://twitter.com/oauth/authorize?oauth_token=" + requestTokenResponse.getFirst("oauth_token"));
                 url = uri.toURL();
                strURLstr=url.toString();
            } catch (java.net.URISyntaxException ex) {
            }
            TwitterJFrame.oAuthURL=url;//transfer oAuthURL from inner class to outter class
            return strURLstr;
       }

        private java.lang.String authorizeConsumer(Form requestTokenResponse) throws IOException {
            String ov2=null;
            ov2=oauth_verifier2;
            return ov2;
    }

        private HostnameVerifier getHostnameVerifier() {
           return new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
                    return true;
                }
            };
        }

        private SSLContext getSSLContext() {
          javax.net.ssl.TrustManager x509 = new javax.net.ssl.X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
                    return;
                }
                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
                    return;
                }
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext ctx = null;
            try {
                ctx = SSLContext.getInstance("SSL");
                ctx.init(null, new javax.net.ssl.TrustManager[]{x509}, null);
            } catch (java.security.GeneralSecurityException ex) {
            }
            return ctx;
        }
    }
}

